package com.cr4y0n.hot100;

/**
 * @author cr4y0n
 * <a href="https://leetcode.cn/problems/add-two-numbers/?envType=study-plan-v2&envId=top-100-liked">两数相加</a>
 * 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
 * 请你将两个数相加，并以相同形式返回一个表示和的链表。
 * 你可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 * 示例 1：
 * 输入：l1 = [2,4,3], l2 = [5,6,4]
 * 输出：[7,0,8]
 * 解释：342 + 465 = 807.
 * 示例 2：
 * 输入：l1 = [0], l2 = [0]
 * 输出：[0]
 * 示例 3：
 * 输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 * 输出：[8,9,9,9,0,0,0,1]
 */
public class _2_AddTwoNumbers {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    static class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int len1 = getLength(l1);
            int len2 = getLength(l2);
            ListNode longer = len1 > len2 ? l1 : l2;
            ListNode shorter = longer == l1 ? l2 : l1;
            ListNode dummy = new ListNode(0);
            ListNode cur = dummy;
            int carry = 0;
            while (shorter != null) {
                int sum = longer.val + shorter.val + carry;
                cur.next = new ListNode(sum % 10);
                carry = sum / 10;
                longer = longer.next;
                shorter = shorter.next;
                cur = cur.next;
            }
            while (longer != null) {
                int sum = longer.val + carry;
                cur.next = new ListNode(sum % 10);
                carry = sum / 10;
                longer = longer.next;
                cur = cur.next;
            }
            if (carry != 0) {
                cur.next = new ListNode(1);
            }
            return dummy.next;
        }

        private int getLength(ListNode head) {
            int len = 0;
            while (head != null) {
                head = head.next;
                len++;
            }
            return len;
        }
    }
}
